package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Loader;
import com.tianxin.workbao.workBao.bean.LoaderDao;
import com.tianxin.workbao.workBao.bean.LoaderUse;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

/**
 * Created by hacker on 2017/7/1.
 */

public class LoaderProvide extends BaseDataProvide {

    private Context mContext;
    private Handler saveDbHandler;
    private List<LoaderUse> mLoaderUses;
    private UpdateListViewListener mListener;
    private List<Loader> mLoaders;
    private int mPage = 1;


    public LoaderProvide(Context context, UpdateListViewListener listener) {
        super(context);
        this.mContext = context;
        mListener = listener;
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        if (disposeDataHandle == null) {
            disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        }
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        if (disposeDataListener == null) {
            disposeDataListener = new DisposeDataListener() {
                @Override
                public void onSuccess(Object responseObj) {
                    mListener.hideProgress();
                    //保存数据库存中
                    saveToDb(responseObj);
                }

                @Override
                public void onFailure(Object reasonObj) {
                    mListener.hideProgress();
                    showRequestErrorMessage(mListener,reasonObj.toString());
                }
            };
        }
        return disposeDataListener;
    }

    @Override
    public void refreshUI() {
        if (mLoaders != null && !mLoaders.isEmpty()) {
            if (mPage > 1) {
                mListener.onLoadMoreData(mLoaders);
            } else {
                mListener.onRefreshData(mLoaders);
            }
        }
    }

    /**
     * 保存到数据中
     *
     * @param obj 请求返回的所有内容
     */
    private void saveToDb(Object obj) {
        try {
            JSONObject jsonObject = new JSONObject(obj.toString());
            int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
            if (status > 0) {
                LoaderDao loaderDao = mGreenDaoHelper.getDaoSession().getLoaderDao();
                String data = jsonObject.getString(Constant.RESPONSE_DATA);
                if (data.startsWith("[") && data.endsWith("]")) {
                    JSONArray array = jsonObject.getJSONArray(Constant.RESPONSE_DATA);
                    if (array.length() > 0) {
                        mLoaders = BeansUtil.loaderToBeans(data);
                        refreshUI();
                        //set the mLoaders value
                        for (int i = 0; i < mLoaders.size(); i++) {
                            loaderDao.insertOrReplace(mLoaders.get(i));
                        }
                    } else {
                        Log.d(Constant.COM_TAG, "response : data is empty !" + obj.toString());
                    }
                } else {
                    Loader loader = BeansUtil.loaderToBean(data);
                    mLoaders.clear();
                    mLoaders.add(loader);
                    refreshUI();
                    loaderDao.insertOrReplace(loader);
                }
            } else {
                Log.d(Constant.COM_TAG, "response : no data !" + obj.toString());
            }
        }catch (Exception e) {
            showRequestErrorMessage(mListener,obj.toString());
            e.printStackTrace();
        }
    }


    /**
     * get loader list
     * one step: get from db
     * two step: if the one step is empty get from server and save in db
     *
     * @return
     */
    public void getLoaderList() {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mListener.hideProgress();
            mListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb();
        } else {
            updateFromServer();
        }
        refreshUI();
    }

    private void updateFromServer() {
        mListener.showProgress();
        String loaderUrl = URL.getLoaderUrl();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME,getAppToken());
        RequestParams params = new RequestParams(map);
        Request postRequest = CommonRequest.createPostRequest(loaderUrl, params);
        CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
    }

    public void getFromDb() {
        LoaderDao loaderDao = mGreenDaoHelper.getDaoSession().getLoaderDao();
        mLoaders = loaderDao.queryBuilder().build().list();
    }
}
